package com.netease.ticket;

import java.io.Console;
import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Scanner;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

/**
 * 
 * @author bjyangfan
 * 自动化流程
 */

public class WebClient {
	
	public HttpClient client;
	public String cookie;
	OrderRequestSubmit orderRequestSubmit;
	ConfirmSubmit confirmSubmit;
	Login log;
	
	
	public WebClient() {
		orderRequestSubmit = new OrderRequestSubmit();
		confirmSubmit =new ConfirmSubmit();
		log = new Login();
	}
	
	/**
	 * 登陆
	 * @param user 用户名
	 * @param pwd 密码
	 * @throws Exception
	 */
	public boolean login(String user, String pwd) throws Exception
	{
		client = log.login(user, pwd);
		if(client == null) return false;
		this.cookie = Util.cookie2String(client.getState().getCookies());
		if(this.cookie == null || this.cookie.isEmpty()){this.cookie = log.cookie;}
		
		orderRequestSubmit.user = user;
		orderRequestSubmit.jsFile = log.jsFile;
		orderRequestSubmit.jsFileRaw = log.jsFileRaw;
		confirmSubmit.user = user;
		
		return true;
	}
	
	/**
	 * 查询
	 * @param date 日期
	 * @param from 出发站
	 * @param to 目的站
	 * @return 车次和该车信息的结果集
	 * @throws Exception
	 */
	public HashMap<String, TrainInfo> query(String date, String from, String to) throws Exception
	{
		QueryInfo qi = new QueryInfo();
		qi.client = client;
		qi.cookie = cookie;
		
		HashMap<String, TrainInfo> result = qi.query(date, from, to);
		return result;
	}
	
	/**
	 * 预定
	 * @param query_str
	 * @throws Exception
	 */
	public boolean submit(HashMap<String, TrainInfo> result, String train_no, String date) throws Exception
	{ 
		 if(result == null) return false;
		 Iterator<Entry<String, TrainInfo>> it = result.entrySet().iterator();
		 TrainInfo ti;
		 while(it.hasNext()){
             Entry<String, TrainInfo>  obj = (Entry<String, TrainInfo>) it.next();
             ti = (TrainInfo)obj.getValue();
             System.out.println("查询到的车次：" + ti.station_train_code + ",开点：" + ti.train_start_time + ",历时："
		 						+ ti.lishi + "\r\n");
		 }
		 
		 train_no = train_no.toUpperCase();

		 //得到我想要预定的火车的信息，点击预订
		 ti = result.get(train_no);
		 
		 if(ti == null)
		 {
			 System.out.println("没有找到相关的车次！");
			 return false;
		 }
		 
		 ti.train_date = date;
		 ti.round_train_date = date; //该值代表意义尚不明确,一般与train_date一致，从字面理解可能是返程日期
		 
		 orderRequestSubmit.copyInfo(ti);
		 confirmSubmit.copyFromTrainInfo(ti);
		 
		 orderRequestSubmit.client = client;
		 orderRequestSubmit.cookie = cookie;
		 
		 //预订该票
		 orderRequestSubmit.preSubmit();
		 return true;
	}
	
	/**
	 * 确认并提交订单
	 */
	public boolean confirm()throws Exception
	{
		confirmSubmit.cookie = this.cookie;
		confirmSubmit.client = this.client;
		
		return confirmSubmit.submit();
	}
	
	public static void main(String[] args) {

		WebClient wc = new WebClient();
		
		//初始化车站信息
		if(!StationInfo.init()) 
		{
			System.out.println("车站代码初始化失败");
			return;
		}
		
		
		try{
			String content = Util.readFile("passenger_info.txt", "GB2312");
			String[] infos = content.split("}");
			if(infos.length < 2) {
				System.out.println("您填写的信息不正确！");
				return;
			}
			
			HashMap<String, String> map = Util.paseSimpleJSON(infos[0]);
			
			//登陆
			login:
			while(true)
			{
				if(wc.login(map.get("user"), map.get("password")) == false)
				{
					System.out.println("登陆失败!");
					
					Thread.sleep(6000);
					continue login;
				}
				
				query:
				while(true){
					//泛查询，指定日期和出到站
					HashMap<String, TrainInfo> result = wc.query(map.get("date"), map.get("from_station"), map.get("to_station"));
					
					//TODO 目前只做了有余票的车次查询，需要做没有余票或者未到预售时间的余票查询
					if(result == null)
					{
						System.out.println("没有查到任何结果，可能信息错误或者所有车票已售完，等待6秒后继续查询...。");
						Thread.sleep(8000);
						continue query;
					}
					else if(result.containsKey("needReLogin"))
					{
						continue login;
					}
				
					//预定车次
					if(false == wc.submit(result, map.get("train_no"), map.get("date")))
					{
						System.out.println("没有找到您要预定的车次,可能是已售完或者未到预售时间，等待6秒后继续查询...");
						Thread.sleep(8000);
						continue query;
					}
					
					//获取乘客信息
					ArrayList<PassengerInfo> list = new ArrayList<PassengerInfo>();
					for(int i = 1; i< infos.length; i++)
					{
						list.add(Util.pasePassengerFile(infos[i]));
					}
		
					//填写个人信息
					wc.confirmSubmit.fillMultiPassengerInfo(list);
					//wc.confirmSubmit.fillPassengerInfo("杨帆", "1", "130682198503077134", "15101047193", "1", "1");
					
					
					//确认成功后才退出
					if(wc.confirm())break login;
					else 
					{
						Thread.sleep(8000);
						continue query;
					}
				}
			}
			//退出
			//wc.log.logout();
		
		}catch(Exception ex) {
			System.out.println(ex.getMessage());
			ex.printStackTrace();
			
		}
	}
	
}
